package com.epc.easypurchase.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import com.epc.easypurchase.R
import com.epc.easypurchase.fragment.HomeFragment
import com.epc.easypurchase.fragment.TestFragment
import com.epc.easypurchase.service.PersonPushIntentService
import com.epc.easypurchase.service.PersonPushService
import com.epc.easypurchase.util.PermissionCheckUtil
import com.epc.easypurchase.util.SimpleDialogUtil
import com.epc.easypurchase.widget.TabMainView
import com.igexin.sdk.PushManager
import com.jiazhuo.blockgamesquare.constant.Constants
import com.jiazhuo.blockgamesquare.http.api.UrlConstainer
import com.jiazhuo.blockgamesquare.util.FragmentManagerHelper
import com.jiazhuo.blockgamesquare.util.ResourceUtil
import com.jiazhuo.blockgamesquare.util.toast
import com.tbruyelle.rxpermissions2.RxPermissions
import com.woochen.baselibrary.base.mvp.BaseMvpActivity
import com.woochen.baselibrary.navigation.bottom.TabBottomNavigation
import com.woochen.baselibrary.navigation.bottom.iterator.ListTabIterator
import com.woochen.baselibrary.util.StatusBarUtil
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseMvpActivity() {
    private var isExit = false
    internal var mHandler: Handler? = object : Handler() {

        override fun handleMessage(msg: Message) {
            isExit = false
        }
    }
    /* private val mTabRes = arrayOf(R.drawable.select_tab_home, R.drawable.select_tab_msg,
             R.drawable.select_tab_my) */
    private val mTabRes = arrayOf(R.drawable.select_tab_home, R.drawable.select_tab_msg,
            R.drawable.select_tab_my, R.drawable.select_tab_my)
    //    private val mTabNames = arrayOf(R.string.tab_main, R.string.tab_msg, R.string.tab_my)
    private val mTabNames = arrayOf(R.string.tab_main, R.string.tab_msg, R.string.tab_my, R.string.web_test)
    private val mTabIterator = ListTabIterator<TabMainView>()
    private val mFragmentManagerHelper by lazy {
        FragmentManagerHelper(supportFragmentManager, R.id.fl_container)
    }

    private var mHomeFragmet: HomeFragment? = null
    private var mMagFragmet: HomeFragment? = null
    private var mMyFragment: HomeFragment? = null
    private var mTestFragment: TestFragment? = null
    private var homePageName: String = ""
    private var msgPageName: String = ""
    private var myPageName: String = ""
    override fun setContentView(): Int = R.layout.activity_main

    companion object {

        private val USER_TYPE: String? = "user_type"

        fun start(context: Context, type: Int) {
            val intent = Intent(context, MainActivity::class.java)
            intent.putExtra(USER_TYPE, type)
            context.startActivity(intent)
        }
    }

    override fun initData() {
        initPush()
        initIntent()
        initBottomNav()
        initFragments()
        requestPermission()
    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_CONTACTS).subscribe({ })
        //notification check
        if (!PermissionCheckUtil.notifycationEnable(mContext)) {
            SimpleDialogUtil.confirmAndCancel(mContext, R.string.tip_notification, R.string.cancle, R.string.open_notify, object : SimpleDialogUtil.SimpleClickListener {
                override fun confirm() {
                    PermissionCheckUtil.gotoSet(mContext)
                }
            })
        }
    }

    private fun initPush() {
        PushManager.getInstance().initialize(this.applicationContext, PersonPushService::class.java)
        PushManager.getInstance().registerPushIntentService(this.applicationContext, PersonPushIntentService::class.java)
    }

    private fun initIntent() {
        val type = intent.getIntExtra(USER_TYPE, 0)
        judgeType(type)
    }

    private fun judgeType(type: Int) {
        when (type) {
            Constants.TYPE_SUPPLY -> {
                homePageName = UrlConstainer.webBaseUrl + UrlConstainer.HOME_PAGE
                msgPageName = UrlConstainer.webBaseUrl + UrlConstainer.PRODUCER_MSG_PAGE
                myPageName = UrlConstainer.webBaseUrl + UrlConstainer.PRODUCER_MY_PAGE
            }
            Constants.TYPE_PURCHASE -> {
                homePageName = UrlConstainer.webBaseUrl + UrlConstainer.HOME_PAGE
                msgPageName = UrlConstainer.webBaseUrl + UrlConstainer.CUSTOMER_MSG_PAGE
                myPageName = UrlConstainer.webBaseUrl + UrlConstainer.CUSTOMER_MY_PAGE
            }
        }
    }


    private fun initFragments() {
        StatusBarUtil.statusBarTintColor(this, R.color.text_normal)
        mHomeFragmet = HomeFragment.newInstance(UrlConstainer.webBaseUrl + UrlConstainer.HOME_PAGE)
        mFragmentManagerHelper.addFragment(mHomeFragmet!!, "main")
    }


    /**
     * 初始化底部导航
     */
    private fun initBottomNav() {
        for (index in mTabNames.indices) {
            val tabMainView = TabMainView.Builder(mContext, R.layout.view_main_tab)
                    .name(ResourceUtil.getString(mTabNames[index]))
                    .icon(mTabRes[index])
                    .build<TabMainView>()
            mTabIterator.addItem(tabMainView)
        }
        tabBottom.addItem(mTabIterator)
        tabBottom.onItemClickListener = object : TabBottomNavigation.OnItemClickListener {
            override fun onItemClick(position: Int) {
                tabBottom.selectItem(position)
                switchTab(position)
            }
        }
    }

    private fun switchTab(position: Int) {
        var fragmentTag = "main"
        mFragmentManagerHelper.swithFragmentAllowingStateLoss(when (position) {
            0 -> {
                StatusBarUtil.statusBarTintColor(this, R.color.text_normal)
                mHomeFragmet ?: run {
                    fragmentTag = "main"
                    mHomeFragmet = HomeFragment.newInstance(homePageName)
                    mHomeFragmet!!
                }
            }

            1 -> {
                StatusBarUtil.statusBarTintColor(this, R.color.colorBlue1)
                mMagFragmet ?: run {
                    println("-> $msgPageName")
                    fragmentTag = "msg"
                    mMagFragmet = HomeFragment.newInstance(msgPageName)
                    mMagFragmet!!
                }
            }
            2 -> {
                StatusBarUtil.statusBarTintColor(this, R.color.colorBlue1)
                mMyFragment ?: run {
                    fragmentTag = "my"
                    mMyFragment = HomeFragment.newInstance(myPageName)
                    mMyFragment!!
                }
            }
            3 -> {
                StatusBarUtil.statusBarTintColor(this, R.color.colorBlue1)
                mTestFragment ?: run {
                    fragmentTag = "test"
                    mTestFragment = TestFragment.newInstance(myPageName)
                    mTestFragment!!
                }
            }
            else -> throw IllegalArgumentException("the index of fragment does not exist!")
        }, fragmentTag)

    }

    override fun onBackPressed() {
        exit()
    }


    private fun exit() {
        if (!isExit) {
            isExit = true
            toast(R.string.exit_app)
            mHandler?.sendEmptyMessageDelayed(0, 2000)
        } else {
            finish()
            System.exit(0)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        val type = intent?.getIntExtra(USER_TYPE, Constants.TYPE_SUPPLY)
        //移除所有的fragment
        mHomeFragmet = HomeFragment.newInstance(UrlConstainer.webBaseUrl + UrlConstainer.HOME_PAGE)
        mFragmentManagerHelper.replaceFragmentAllowingStateLoss(mHomeFragmet!!, "main")
        tabBottom.selectItem(0)
        judgeType(type!!)
        mMagFragmet = null
        mMyFragment = null
        mTestFragment = null
    }

}
